#include "Material.h"
#include <iostream>
using namespace std;


Material::Material(ID3DXEffect *effect)
	:effect(effect)
{
}

void Material::SetValue( std::string name, int value )
{
	intTable[name] = value;
}
void Material::SetValue( std::string name, float value)
{
	floatTable[name] = value;
}
void Material::SetValue( std::string name, D3DXMATRIX value)
{
	matrixTable[name] = value;
}
void Material::SetValue( std::string name, D3DXVECTOR4 value)
{
	vectorTable[name] = value;
}
void Material::SetValue( std::string name, IDirect3DTexture9 *value)
{
	textureTable[name] = value;
}

void Material::UpdateShaderConsts()
{
	D3DXHANDLE hndl;

	map< string, int >::iterator intIter;
	for( intIter = intTable.begin(); intIter != intTable.end(); ++intIter )
	{
		hndl = effect->GetParameterByName(0, intIter->first.c_str() );
		if(hndl)
			effect->SetFloat(hndl,intIter->second);
		else
			cout << "Set shader parameter failed" << endl;
	}

	map< string, float >::iterator floatIter;
	for( floatIter = floatTable.begin(); floatIter != floatTable.end(); ++floatIter )
	{
		hndl = effect->GetParameterByName(0, floatIter->first.c_str() );
		if(hndl)
			effect->SetFloat(hndl,floatIter->second);
		else
			cout << "Set shader parameter failed" << endl;
	}

	map< string, D3DXMATRIX >::iterator matIter;
	for( matIter = matrixTable.begin(); matIter != matrixTable.end(); ++matIter )
	{
		hndl = effect->GetParameterByName(0, matIter->first.c_str() );
		if(hndl)
			effect->SetMatrix(hndl, &matIter->second);
		else
			cout << "Set shader parameter failed" << endl;
	}


	map< string, D3DXVECTOR4 >::iterator vecIter;
	for( vecIter = vectorTable.begin(); vecIter != vectorTable.end(); ++vecIter )
	{
		hndl = effect->GetParameterByName(0, vecIter->first.c_str() );
		if(hndl)
			effect->SetVector(hndl, &vecIter->second);
		else
			cout << "Set shader parameter failed" << endl;
	}

	map< string, IDirect3DTexture9* >::iterator texIter;
	for( texIter = textureTable.begin(); texIter != textureTable.end(); ++texIter )
	{
		hndl = effect->GetParameterByName(0, texIter->first.c_str() );
		if(hndl)
			effect->SetTexture(hndl, texIter->second);
		else
			cout << "Set shader parameter failed" << endl;
	}
}

ID3DXEffect *Material::GetEffect()
{
	return effect;
}